
// TopoOptimizeDlg.cpp : implementation file
//

#include "stdafx.h"
#include "TopoOptimize.h"
#include "TopoOptimizeDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif
UINT CVectorKey::s_nDimension=256;

// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// CTopoOptimizeDlg dialog




CTopoOptimizeDlg::CTopoOptimizeDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CTopoOptimizeDlg::IDD, pParent)
	, m_nNodeNumber(0)
	, m_nPivotNumber(256)
	, m_nSimpleNumber(5000)
	, m_nGranularity(20)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CTopoOptimizeDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_EDIT1, m_nNodeNumber);
	DDX_Text(pDX, IDC_EDIT2, m_nPivotNumber);
	DDX_Text(pDX, IDC_EDIT3, m_nSimpleNumber);
	DDX_Text(pDX, IDC_EDIT4, m_nGranularity);
}

BEGIN_MESSAGE_MAP(CTopoOptimizeDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_BUTTON_IMPORT_NODE_LATENCY, &CTopoOptimizeDlg::OnBnClickedButtonImportNodeLatency)
	ON_BN_CLICKED(IDC_BUTTON_DRAW, &CTopoOptimizeDlg::OnBnClickedButtonDrawPoint)
	ON_BN_CLICKED(IDC_BUTTON_DRAW_LINE, &CTopoOptimizeDlg::OnBnClickedButtonDrawLine)
END_MESSAGE_MAP()


// CTopoOptimizeDlg message handlers

BOOL CTopoOptimizeDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here
	srand(GetTickCount());

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CTopoOptimizeDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CTopoOptimizeDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CTopoOptimizeDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}


void CTopoOptimizeDlg::OnBnClickedButtonImportNodeLatency()
{
	// TODO: Add your control notification handler code here
	CFileDialog cFile(TRUE,0,"DistanceTable.txt",4|2,"Text Files (*.txt)|*.txt||");
	if(cFile.DoModal()==IDOK)
	{
		const int MAX =0xffff;
		int nSize = 0;
		ifstream fin(cFile.GetPathName().GetBuffer());
		if(fin.is_open()==false)
		{
			this->MessageBox("Open file error","ERROR",MB_OK|MB_ICONERROR);
			return ;
		}
		else
		{
			vector<int> cTmpVec;
			int nTmp;
			while(fin>>nTmp)
			{
				if(nTmp<0)
				{
					nTmp=MAX;
				}
				cTmpVec.push_back(nTmp);
			}
			int nSize = (int)cTmpVec.size();
			int nLine = (int)sqrt((double)nSize);
			if(nSize!=nLine*nLine)
			{
				this->MessageBox("File error","ERROR",MB_OK|MB_ICONERROR);
				return ;
			}
			else
			{
				vector<int> t(nLine);
				m_rgDistanceTable.assign(nLine,t);
				for(int i=0;i<nLine;i++)
				{
					for(int j=0;j<nLine;j++)
					{
						m_rgDistanceTable[i][j]=cTmpVec[i*nLine+j];
					}
				}
			}
			this->m_nNodeNumber = nLine;
			this->UpdateData(FALSE);

			this->MessageBox("Success");
		}
	}
}

void CTopoOptimizeDlg::OnBnClickedButtonDrawPoint()
{
	// TODO: Add your control notification handler code here
	this->UpdateData();
	CVectorKey::SetDimension(this->m_nPivotNumber);
	vector<unsigned int> cPivot;
	GetRandomSequence(0,this->m_nNodeNumber,this->m_nPivotNumber,cPivot);
	CString strCurDir;
	GetModuleFileName(NULL, strCurDir.GetBufferSetLength(MAX_PATH), MAX_PATH);
	strCurDir.Delete(strCurDir.ReverseFind('\\')+1,strCurDir.GetLength()-1-strCurDir.ReverseFind('\\'));
	
	strCurDir.Append("Results\\");
	CString strData,strScript,strGraph;
	strData.Format("%s%d_%s",strCurDir.GetString(),this->m_nPivotNumber,"Data.dat");
	strScript.Format("%s%d_%s",strCurDir.GetString(),this->m_nPivotNumber,"Draw.plt");
	strGraph.Format("%s%d_%s",strCurDir.GetString(),this->m_nPivotNumber,"Vector_Delay.eps");
	ofstream fout(strData.GetString());
	if(fout)
	{
		for(unsigned i = 0;i<m_nSimpleNumber;i++)
		{
			int nFirst = rand()%m_nNodeNumber;
			int nSecond;
			do
			{
				nSecond = rand()%m_nNodeNumber;
			}while(nFirst==nSecond);
			CVectorKey cKey1,cKey2;
			for(unsigned j = 0;j<m_nPivotNumber;++j)
			{
				cKey1.m_rgId[j]=(float)this->m_rgDistanceTable[nFirst][cPivot[j]];
				cKey2.m_rgId[j]=(float)this->m_rgDistanceTable[nSecond][cPivot[j]];
			}
			fout<<CVectorKey::GetDistance(cKey1,cKey2)<<" "<<m_rgDistanceTable[nFirst][nSecond]<<endl;
		}
	}
	fout.close();
	CString script("reset \nset term postscript eps color enhanced \n");
	script.AppendFormat("set title 'Relationship between Vector COS and Delay'\n");
	script.AppendFormat("set output '%s'\n",strGraph.GetString());
	script.AppendFormat("set key top right\n");
	script.AppendFormat("set xlabel 'Vector Cos' \n");
	script.AppendFormat("set ylabel 'Delay Time(ms)'\n");
	script.AppendFormat("plot '%s' using 1:2 title 'Dimension:%u'\n",strData.GetString(),this->m_nPivotNumber);
	script.AppendFormat("set term windows\n");
	script.AppendFormat("replot\n");
	FILE *pFile ;
	if(0==fopen_s(&pFile,strScript.GetString(),"w"))
	{
		fwrite(script.GetBuffer(),1,script.GetLength(),pFile);
		fclose(pFile);
		CString cmd;
		cmd.Format("pgnuplot.exe -persist \"%s\"",strScript.GetString());
		WinExec(cmd.GetString(),SW_SHOW);
	}
	else
	{
		MessageBox("Open File Error!");
	}
}

void CTopoOptimizeDlg::OnBnClickedButtonDrawLine()
{
	this->UpdateData();
	CVectorKey::SetDimension(this->m_nPivotNumber);
	vector<unsigned int> cPivot;
	GetRandomSequence(0,this->m_nNodeNumber,this->m_nPivotNumber,cPivot);
	CString strCurDir;
	GetModuleFileName(NULL, strCurDir.GetBufferSetLength(MAX_PATH), MAX_PATH);
	strCurDir.Delete(strCurDir.ReverseFind('\\')+1,strCurDir.GetLength()-1-strCurDir.ReverseFind('\\'));
	
	strCurDir.Append("Results\\");
	CString strData,strScript,strGraph;
	strData.Format("%s%d_%s",strCurDir.GetString(),this->m_nPivotNumber,"Data.dat");
	strScript.Format("%s%d_%s",strCurDir.GetString(),this->m_nPivotNumber,"Draw.plt");
	strGraph.Format("%s%d_%s",strCurDir.GetString(),this->m_nPivotNumber,"Vector_Delay.eps");
	ofstream fout(strData.GetString());
	vector<pair<float,int>> cDataVector;
	float fMin=(float)(0xffffff),fMax=0;
	if(fout)
	{
		for(unsigned i = 0;i<m_nSimpleNumber;i++)
		{
			int nFirst = rand()%m_nNodeNumber;
			int nSecond;
			do
			{
				nSecond = rand()%m_nNodeNumber;
			}while(nFirst==nSecond);
			CVectorKey cKey1,cKey2;
			for(unsigned j = 0;j<m_nPivotNumber;++j)
			{
				cKey1.m_rgId[j]=(float)this->m_rgDistanceTable[nFirst][cPivot[j]];
				cKey2.m_rgId[j]=(float)this->m_rgDistanceTable[nSecond][cPivot[j]];
			}
			float fDis = CVectorKey::GetDistance(cKey1,cKey2);
			cDataVector.push_back(make_pair(fDis,m_rgDistanceTable[nFirst][nSecond]));
			fMin = min(fMin,fDis);
			fMax = max(fMax,fDis);
		}
		map<float,CCalculator> cCal;
		float fStep = (fMax-fMin)/this->m_nGranularity;
		for(unsigned i = 0;i<this->m_nGranularity;++i)
		{
			cCal.insert(make_pair(fMin+i*fStep,CCalculator()));
		}
		for(unsigned i = 0;i<cDataVector.size();++i)
		{
			map<float,CCalculator>::iterator it = cCal.lower_bound(cDataVector[i].first);
			if(it!=cCal.end())
			{
				it->second.Add(cDataVector[i].second);
			}
		}
		for(map<float,CCalculator>::iterator it = cCal.begin();it!=cCal.end();++it)
		{
			it->second.Calculate();
			fout<<it->first+fStep/2<<" "<<it->second.GetEven()<<" "<<it->second.GetEven()-it->second.GetSDev()<<" "<<it->second.GetEven()+it->second.GetSDev()<<endl;
		}
	}
	fout.close();
	CString script("reset \nset term postscript eps color enhanced \n");
	script.AppendFormat("set title 'Relationship between Vector COS and Delay'\n");
	script.AppendFormat("set output '%s'\n",strGraph.GetString());
	script.AppendFormat("set key top right\n");
	script.AppendFormat("set xlabel 'Vector Cos' \n");
	script.AppendFormat("set ylabel 'Delay Time(ms)'\n");
	script.AppendFormat("plot '%s' using 1:2:3:4 title 'Dimension:%u' with yerrorbars\n",strData.GetString(),this->m_nPivotNumber);
	script.AppendFormat("set term windows\n");
	script.AppendFormat("replot\n");
	FILE *pFile ;
	if(0==fopen_s(&pFile,strScript.GetString(),"w"))
	{
		fwrite(script.GetBuffer(),1,script.GetLength(),pFile);
		fclose(pFile);
		CString cmd;
		cmd.Format("pgnuplot.exe -persist \"%s\"",strScript.GetString());
		WinExec(cmd.GetString(),SW_SHOW);
	}
	else
	{
		MessageBox("Open File Error!");
	}
}
